package com.xusheng.cli.controller.proxy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.backAgentModule.BackAgent;
import com.xusheng.cli.entity.proxyHostModule.ProxyHost;
import com.xusheng.cli.entity.proxyHostModule.ProxyHostVO;
import com.xusheng.cli.entity.proxyHostThreeModule.ProxyHostThree;
import com.xusheng.cli.entity.proxyHostTwoModule.ProxyHostTwo;
import com.xusheng.cli.service.BackAgentService;
import com.xusheng.cli.service.ProxyHostService;
import com.xusheng.cli.service.ProxyHostThreeService;
import com.xusheng.cli.service.ProxyHostTwoService;
import com.xusheng.cli.tools.CurrentProxyUserUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代理--域名(ProxyHost)表控制层
 *
 * @author whr
 * @since 2024-03-20 14:01:55
 */
@Validated
@RestController
@RequestMapping("/proxy/v1/proxyHost")
public class ProxyHostController {
    /**
     * 服务对象
     */
    @Resource
    private ProxyHostService proxyHostService;
    @Resource
    private ProxyHostTwoService proxyHostTwoService;
    @Resource
    private ProxyHostThreeService proxyHostThreeService;

    @Resource
    private BackAgentService backAgentService;

    /**
     * 查询所有数据
     *
     * @param proxyHost 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-20 14:01:55
     */
    @GetMapping("queryAll")
    public Result<List<ProxyHost>> queryAll(ProxyHost proxyHost) {
        return Result.success(proxyHostService.list(new QueryWrapper<>(proxyHost)));
    }

    /**
     * 分页查询所有数据
     *
     * @param page      分页对象
     * @param proxyHost 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-20 14:01:55
     */
    @GetMapping("queryByPage")
    public Result<MyPage<ProxyHost>> queryByPage(MyPage<ProxyHost> page, ProxyHost proxyHost) {
        return Result.success(proxyHostService.page(page, new QueryWrapper<>(proxyHost)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     * @author whr
     * @since 2024-03-20 14:01:55
     */
    @GetMapping("queryOne/{id}")
    public Result<ProxyHost> selectOne(@PathVariable Serializable id) {
        return Result.success(proxyHostService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param proxyHost 实体对象
     * @return 新增结果
     * @author whr
     * @since 2024-03-20 14:01:55
     */
    @PostMapping("insert")
    public Result<Object> insert(@Validated(Save.class) @RequestBody ProxyHost proxyHost) {
        return Result.isSuccess(proxyHostService.save(proxyHost));
    }

    /**
     * 修改数据
     *
     * @param proxyHost 实体对象
     * @return 修改结果
     * @author whr
     * @since 2024-03-20 14:01:55
     */
    @PutMapping("update")
    public Result<Object> update(@Validated(Update.class) @RequestBody ProxyHost proxyHost) {
        return Result.isSuccess(proxyHostService.updateById(proxyHost));
    }

    /**
     * 删除单条数据
     *
     * @param id 主键
     * @return 删除结果
     * @author whr
     * @since 2024-03-20 14:01:55
     */
    @DeleteMapping("delete/{id}")
    public Result<Object> delete(@PathVariable Long id) {
        ProxyHost proxyHost = new ProxyHost();
        proxyHost.setId(id);
        return Result.isSuccess(proxyHostService.removeById(proxyHost));
    }

    /**
     * 批量删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     * @author whr
     * @since 2024-03-20 14:01:55
     */
    @DeleteMapping("batchDelete")
    public Result<Object> batchDelete(@Validated @Size(min = 1, message = "缺少删除所需的id") @RequestParam("idList") List<Long> idList) {
        return Result.isSuccess(proxyHostService.batchDelete(idList, new ProxyHost()));
    }

    /**
     * 获取域名
     *
     * @param proxyHost
     * @return
     */
    @GetMapping("getHostByProxyId")
    public Result<List<ProxyHost>> selectOptions(ProxyHost proxyHost) {
        if (proxyHost.getProxyId() == null) {
            proxyHost.setProxyId(CurrentProxyUserUtil.getUserId());
        }
        BackAgent backAgent = backAgentService.getById(proxyHost.getProxyId());
        Integer level = backAgent.getLevel();
        List<ProxyHost> list = new ArrayList<>();
        if (level == 1) {
            list = proxyHostService.lambdaQuery().eq(ProxyHost::getProxyId, proxyHost.getProxyId()).list();
        } else if (level == 2) {
            list = proxyHostService.selectOptionsTwo(proxyHost);
        } else if (level == 3) {
            list = proxyHostService.selectOptionsThree(proxyHost);
        }
        return Result.success(list);
    }

    @PostMapping("setHosts")
    @Transactional
    public Result<Object> setHosts(@RequestBody ProxyHostVO proxyHostVO) {
        // 查询分配的代理是几级的
        BackAgent backAgent = backAgentService.getById(proxyHostVO.getProxyId());
        Integer level = backAgent.getLevel();
        List<Long> ids = proxyHostVO.getIds();

        if (level == 2) {
            // 查询原来的数据
            List<ProxyHostTwo> proxyHostTwoList = proxyHostTwoService.lambdaQuery().eq(ProxyHostTwo::getProxyId, proxyHostVO.getProxyId()).list();
            List<Long> hostIds = proxyHostTwoList.stream().map(proxyHostTwo -> proxyHostTwo.getHostId()).collect(Collectors.toList());
            // 删除原来的数据
            proxyHostTwoService.remove(new LambdaQueryWrapper<>(new ProxyHostTwo()).eq(ProxyHostTwo::getProxyId, proxyHostVO.getProxyId()));
            // 重置一级数据中配分状态
            if (!hostIds.isEmpty()) {
                proxyHostService.lambdaUpdate().set(ProxyHost::getAllocation, false).in(ProxyHost::getId, hostIds).update();
            }
            //重新插入
            if (!ids.isEmpty()) {
                List<ProxyHostTwo> proxyHostTwos = new ArrayList<>();
                for (Long id : ids) {
                    ProxyHostTwo proxyHostTwo = new ProxyHostTwo();
                    proxyHostTwo.setHostId(id);
                    proxyHostTwo.setProxyId(proxyHostVO.getProxyId());
                    // 获取分配状态
                    ProxyHostThree one = proxyHostThreeService.lambdaQuery().eq(ProxyHostThree::getHostId, id).one();
                    if (one != null) {
                        proxyHostTwo.setAllocation(true);
                    } else {
                        proxyHostTwo.setAllocation(false);
                    }
                    proxyHostTwos.add(proxyHostTwo);
                }
                proxyHostTwoService.saveBatch(proxyHostTwos);
                // 一级数据中配分状态
                proxyHostService.lambdaUpdate().set(ProxyHost::getAllocation, true).in(ProxyHost::getId, ids).update();
            }
        } else if (level == 3) {
            // 查询原来的数据
            List<ProxyHostThree> proxyHostThreeList = proxyHostThreeService.lambdaQuery().eq(ProxyHostThree::getProxyId, proxyHostVO.getProxyId()).list();
            List<Long> hostIds = proxyHostThreeList.stream().map(proxyHostThree -> proxyHostThree.getHostId()).collect(Collectors.toList());
            // 删除原来的数据
            proxyHostThreeService.remove(new LambdaQueryWrapper<>(new ProxyHostThree()).eq(ProxyHostThree::getProxyId, proxyHostVO.getProxyId()));
            if (!hostIds.isEmpty()) {
                // 重置二级数据中配分状态
                proxyHostTwoService.lambdaUpdate().set(ProxyHostTwo::getAllocation, false).in(ProxyHostTwo::getHostId, hostIds).update();
            }
            //重新插入
            if (!ids.isEmpty()) {
                List<ProxyHostThree> proxyHostThrees = new ArrayList<>();
                for (Long id : ids) {
                    ProxyHostThree proxyHostThree = new ProxyHostThree();
                    proxyHostThree.setHostId(id);
                    proxyHostThree.setProxyId(proxyHostVO.getProxyId());
                    proxyHostThree.setAllocation(false);
                    proxyHostThrees.add(proxyHostThree);
                }
                proxyHostThreeService.saveBatch(proxyHostThrees);
                // 二级数据中配分状态
                proxyHostTwoService.lambdaUpdate().set(ProxyHostTwo::getAllocation, true).in(ProxyHostTwo::getHostId, ids).update();
            }
        }
        return Result.success();
    }
}

